#!/usr/bin/env python
# encoding: utf-8
"""
@author:shucheng
@file:file_util.py
@time:2024/1/4 12:27
@desc 文件操作工具类
"""
import os.path

from pr_properties import pr_properties


def get_project_path():
    """
    获取项目根路径
    :return:
    """
    # 获取当前文件的绝对路径
    current_file = os.path.abspath(__file__)
    # 获取当前文件所在目录的绝对路径
    current_directory = os.path.dirname(current_file)
    # 获取当前项目的根目录
    return os.path.dirname(os.path.dirname(current_directory))


def read_string_from_file(file_relative_path):
    """
    将文件内容读取成字符串返回
    :param file_relative_path: 相对路径
    :return:
    """
    file_path = get_project_file(file_relative_path)
    try:
        with open(file_path, 'r', encoding="utf-8") as f:
            return f.read()
    except FileNotFoundError:
        return None


def get_project_file(file_relative_path):
    """
    使用相对路径获取项目下的文件
    :param file_relative_path:
    :return:
    """
    return os.path.join(get_project_path(), file_relative_path)


def read_property(file_relative_path, key):
    """
    从properties文件中读取属性
    :param file_relative_path:
    :param key:
    :return:
    参考链接：https://blog.csdn.net/Franciz777/article/details/128845356
    https://gitee.com/FrancizTest_admin/pr_properties
    """
    properties_file_path = get_project_file(file_relative_path)
    p = pr_properties.read(properties_file_path)
    return p[key]


def write_property(file_relative_path, key, value):
    """
    将key-value写入properties文件
    :param file_relative_path:
    :param key:
    :param value:
    :return:
    """
    properties_file_path = get_project_file(file_relative_path)
    p = pr_properties.read(properties_file_path)
    p[key] = value
    p.write()


def ensure_dir_exists(dir_path):
    """
    确保目录存在
    :param dir_path:
    :return:
    """
    # 如果文件夹不存在，则先创建文件夹
    if not os.path.exists(abs_dir_path := os.path.abspath(dir_path)):
        os.makedirs(abs_dir_path)


def ensure_parent_dir_exists(file_path):
    """
    确保文件所在路径的父级文件夹存在，如果不存在，则先创建父级文件夹
    :param file_path:
    :return:
    """
    # 如果父级文件夹不存在，则先创建父级文件夹
    abs_file_path = os.path.abspath(file_path)
    if not os.path.exists(parent_dir := os.path.dirname(abs_file_path)):
        os.makedirs(parent_dir)


if __name__ == '__main__':
    m_list = ['1.pdf', '2.pdf', '15.pdf', '3.pdf']
    print(m_list)
    m_list.sort(key=lambda obj: int(obj.split('.')[0]))
    print(m_list)
